<template> 
  <div class="app-container">
    <div class="table-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="输入搜索:">
          <el-input v-model="listQuery.keyword" placeholder="角色名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearchList">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            style="float:right"
            @click="handleResetSearch()"
          >
            重置
          </el-button>
        </el-form-item>

        <el-button type="primary" style="float: right;" @click="handleAdd">添加</el-button>
      </el-form>
      <el-table ref="adminTable"
                :data="list"
                v-loading="listLoading" border
                :header-cell-style="tableHeaderColor">
        <el-table-column label="角色id" width="100" align="center">
          <template slot-scope="scope">{{scope.row.roleId}}</template>
        </el-table-column>
        <el-table-column label="角色名称" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
        <el-table-column label="角色简介" align="center">
          <template slot-scope="scope">{{scope.row.description}}</template>
        </el-table-column>
        <el-table-column label="状态" width="140" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleStatusChange(scope.$index, scope.row)"
              :active-value="0"
              :inactive-value="1"
              v-model="scope.row.status">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" width="160" align="center">
          <template slot-scope="scope">{{scope.row.createDate | formatDateTime}}</template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button size="mini"
                       icon="el-icon-star-off"
                       type="warning" round
                       @click="setMenu(scope.row)">分配菜单
            </el-button>
            <el-button size="mini"
                       icon="el-icon-edit"
                       type="primary" round
                       @click="handleUpdate(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button size="mini"
                       icon="el-icon-delete"
                       type="danger" round
                       @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="isEdit?'编辑':'添加'"
      :visible.sync="dialogVisible"
      width="40%">
      <el-form :model="froms"
               :rules="rules"
               ref="froms"
               label-width="150px" size="small">
        <el-form-item label="角色名称：" prop="name">
          <el-input v-model="froms.name" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" v-model="froms.description" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="角色状态：">
          <el-radio-group v-model="froms.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm('froms')" size="small">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配权限"
      :visible.sync="allocDialogVisible"
      width="30%">
      <el-tree
        :data="ruleAll"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        highlight-current
        :default-checked-keys="userRole"
        :props="userRole">
      </el-tree>
      <div style="margin-top: 20px" align="center">
        <el-button type="primary" @click="saveRole()">保存</el-button>
        <el-button @click="handleClear()">清空</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {delRoles, listPageRole, listRoleMenu, saveRoles,saveRoleMenu} from '@/api/roles';
  import {formatDate} from '@/utils/date';

  // 查询对象
  const defaultListQuery = {
    pageNum: 1,
    pageSize: 10,
    keyword: null
  };

  // 默认表单对象
  const defaultDTO = {
    roleId: null,
    name: null,
    status: 0,
    description: null
  };

  // 默认页面数据
  export default {
    name: 'adminList',
    data() {
      return {
        // 查询对象
        listQuery: Object.assign({}, defaultListQuery),
        // 数据列表
        list: null,
        // 分页推向
        total: null,
        listLoading: false,
        dialogVisible: false,
        // 表单对象
        froms: Object.assign({}, defaultDTO),
        isEdit: false,
        allocDialogVisible: false,
        rules: {
          name: [
            {required: true, message: '请输入角色名称', trigger: 'blur'},
            {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ]
        },
        ruleAll:[],
        userRole:[],
        roleId: null
      }
    },
    created() {
      this.getList();
    },
    filters: {
      formatDateTime(time) {
        if (time == null || time === '') {
          return 'N/A';
        }
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    methods: {
      tableHeaderColor({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
          return "background-color:#efefef;color:#333";
        }
      },
      handleResetSearch() {
        this.listQuery = Object.assign({}, defaultListQuery);
      },
      setMenu(row) {
        this.allocDialogVisible = true;
        listRoleMenu(row.roleId).then(response => {
          this.ruleAll = response.data.roleList;
          let roleArr = response.data.userRoleList;
          let checkedMenuIds=[];
          if(roleArr!=null && roleArr.length>0){
            for(let i=0;i<roleArr.length;i++){
              let menu = roleArr[i];
              if(menu.type !== '0'){
                checkedMenuIds.push(menu.id);
              }
            }
          }
          this.userRole = checkedMenuIds;
          this.roleId = row.roleId
        });
      },
      handleSearchList() {
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },
      handleAdd() {
        this.dialogVisible = true;
        this.isEdit = false;
        this.froms = Object.assign({}, defaultDTO);
        if(this.$refs['froms'] !== undefined){
          this.$refs['froms'].resetFields();
        }
      },
      handleStatusChange(index, row) {
        this.$confirm('是否要修改该状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let req = {
            roleId: row.roleId,
            status: row.status
          };
          saveRoles(req).then(response => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消修改'
          });
          this.getList();
        });
      },
      handleDelete(index, row) {
        this.$confirm('是否要删除该菜单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delRoles(row.roleId).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
          });
        }).catch(() => {
        });;
      },
      handleUpdate(index, row) {
        this.dialogVisible = true;
        this.isEdit = true;
        if(this.$refs['froms'] !== undefined){
          this.$refs['froms'].resetFields();
        }
        this.froms = Object.assign({}, row);
      },
      handleDialogConfirm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否提交数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              saveRoles(this.froms).then(response => {
                this.$message({
                  message: '操作成功！',
                  type: 'success'
                });
                this.dialogVisible = false;
                this.getList();
              })
            }).catch(() => {
            });;
          }
        });
      },
      getList() {
        this.listLoading = true;
        listPageRole(this.listQuery).then(response => {
          this.listLoading = false;
          this.list = response.data.records;
          this.total = response.data.total;
        });
      },
      saveRole() {
        let checkedNodes = this.$refs.tree.getCheckedNodes();
        let tempArr = [];

        console.log(checkedNodes)

        if(checkedNodes!=null&&checkedNodes.length>0){
          for(let i=0;i<checkedNodes.length;i++){
            let checkedNode = checkedNodes[i];
            tempArr.push(checkedNode.id)
            if(checkedNode.pid!== '0'){
              tempArr.push(checkedNode.pid)
            }
          }
        }
        console.log(tempArr)
        var reqArr=[];
        for (var i = 0; i < tempArr.length; i++) {
          if(reqArr.indexOf(tempArr[i])==-1){
            reqArr.push(tempArr[i]);
          }
        }

        console.log(this.roleId)

        let params = {
          roleId: this.roleId,
          pageIds: reqArr.join(',')

        }
        console.log(params)
        this.$confirm('是否分配菜单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
          saveRoleMenu(params).then(response => {
            this.$message({
              message: '分配成功',
              type: 'success',
              duration: 1000
            });
            this.$router.go(0);
          })
        }).catch(() => {
        });
      },
      handleClear() {
        this.$refs.tree.setCheckedKeys([]);
      }
    }
  }
</script>
<style></style>


